<?php
/**
 *@author sparkguo 
 *@date 2017-09-22 交运对帐，更新真实物流费用与称重
 */
defined('BASEPATH') OR exit('No direct script access allowed');
class CheckExpressPrice extends CI_Controller{

    function __construct(){
        parent::__construct();
        $this->load->model('Function_m', 'fun');
        $this->pageSize = $this->config->item('pagenum');
    }

    function ajaxbutton(){
		$action = $other = $this->input->get_post('op');;
		switch($action){
            case "outputExl":
                $this->outputExl();
            break;
            case "outputExl2":
                $this->outputExl2();
            break;
            case "updateRealExpPrice":
                $this->updateRealExpPrice();
            break;
            case "doUpdateCheckResult":
                $this->doUpdateCheckResult();
            break;
            case "resultCheckdetail":
                $this->resultCheckdetail();
            break;
            case "updateCheckResult"://备注异常功能
                $this->updateCheckResult();
            break;
            case "sameup":
                $this->updateSameOrder();
            break;
		}
	}
    
    //交运订单对账
    public function checkDataValidity(){
        require dirname(__FILE__)."/../../fuman/ClassesExcel/PHPExcel.php";
        //交运类型必须选择
        $deliverType = $this->input->post('deliverType');
        if(!$deliverType){
            echo "必须选择交运方式";exit;
        }
        //if(in_array($deliverType,array(1,2,3,4,5,10,14))){//DHL CNE UBI YIDA 中通-------------
            $this->doCheckExpress($deliverType);
            exit;
        //} 
    }
    
    
    public function updateSameOrder(){
        $same_shipinfo=$this->fun->getdatabasesdetail('db_express_check'," AND id=6987");
        $exist_infos=json_decode($same_shipinfo['exist_json'],true);
        $new_arr=array();
        foreach($exist_infos as $key=>$val){
            $new_arr[$val['deliverNumber']][]=$val;
            $new_arr[$val['deliverNumber']]['ship_fre']+=$val['deliverFee'];  
            $new_arr[$val['deliverNumber']]['ship_weight']+=$val['deliverWeight'];    
        }
    
        $needup_datas=array();
        $scanorder_updatas[]=array("real_freight"=>$expinfo['deliverFee'],'batch_shipping_number'=>$expinfo['deliverNumber']);

        $arr_plat['shipping_realfee']=$expinfo['deliverFee']*$point_val;
        $arr_plat['orderweight']=$deliverWeight;$arr_plat['shipping_number']=$expinfo['deliverNumber'];
        $arr_plats[]=$arr_plat;
        
        foreach($new_arr as $key=>$val){
            if(count($val)>3){
                $needup_datas[]=array('exp_number'=>$val[0]['orderId'],'fre'=>$val['ship_fre']);
                
                $scanorder_updatas[]=array("real_freight"=>$val['ship_fre'],'batch_shipping_number'=>$val[0]['deliverNumber']);
                $arr_plats[]=array('shipping_realfee'=>$val['ship_fre'],'orderweight'=>$val['ship_weight']*1000,'shipping_number'=>$val[0]['deliverNumber']);
            }
        }
        //dump($scanorder_updatas);
        //dump($arr_plats);
        
        if(count($needup_datas)>0){
            $this->db->update_batch('db_mabang_scanorder', $scanorder_updatas, 'batch_shipping_number');//批量更新
            echo $this->db->last_query();
            $this->db->update_batch('db_order_list', $arr_plats, 'shipping_number');//批量更新
        }

        
            
    }
    
    public function doCheckExpress($deliver_type_val){
        set_time_limit(0);
        $selectMonth=$this->input->post("selectMonth");
        $deliverType=$this->input->post("deliverType");
        $this->tpl->assign('selectMonth',$selectMonth);
        $this->tpl->assign('deliverType',$deliverType);
        if(!$selectMonth){
            echo "必须选择对帐月份";exit;
        }
        $deliver_type=array(1=>"顺丰",2=>'UPS',3=>'DHL',4=>'CNE',5=>'UBI',6=>'云途',7=>'燕文',8=>'E邮宝线下上海或CNPOST',9=>"无忧物流",10=>"日本邮政",11=>'CNPOST',12=>'佳成物流',14=>'中通快递',15=>'联邦');
        $arr_excel_file = $_FILES['file_excel'];
        if(!empty($arr_excel_file) && $arr_excel_file['error']==0) {
            $fileName = $arr_excel_file["name"];
            $tmpFileName = $arr_excel_file["tmp_name"];
            $fileExtName = explode(".", $fileName);
            if (!($fileExtName[1] == "xls" || $fileExtName[1] == "xlsx")) {//扩展名判断
                echo "上传的文件扩展名应该为.xls或.xlsx";
                exit;
            }
            if ($fileExtName[1] == 'xlsx') {
                $objReader = new PHPExcel_Reader_Excel2007();
                $objExcel = $objReader->load($tmpFileName);
            } else if ($fileExtName[1] == 'xls') {
                $objReader = new PHPExcel_Reader_Excel5();
                $objExcel = $objReader->load($tmpFileName);
            }

            $result=$this->checkExpPriec($objExcel,$deliver_type_val);
            $web_title=$deliver_type[$deliver_type_val]."对帐结果";
            $this->tpl->assign('web_title',$web_title);
            $this->tpl->assign('chargeslist',$result[0]);
            $this->tpl->assign('total_money',$result[1]);
            $this->tpl->assign('fuman_money',$result[2]);
            $this->tpl->assign('chajia_money',$result[3]);
            if($result[5]==''){$result[5]=array();}
            if($result[6]==''){$result[6]=array();}
            $alldata_json=json_encode(array_merge($result[0],$result[5]));
            $existdata_json=json_encode($result[4]);
            $notexistdata_json=json_encode(array_merge($result[5],$result[6]));
            $tpl_data=array("alldata_json"=>$alldata_json,'existdata_json'=>$existdata_json,
            'notexistdata_json'=>$notexistdata_json,'notexistdata'=>$result[5],'waring_arr'=>$result[6],'notexist_total'=>count($result[5]),
            'waring_total'=>$result[7]['waring_total'],'zhifa_money'=>$result[7]['zhifa_money'],'haiwai_money'=>$result[7]['haiwai_money'],
            'waring_json'=>json_encode($result[7]['waring_json']),'green_json'=>json_encode($result[7]['green_json'])
            ,'notexist_json'=>json_encode($result[5]));
            
            $this->tpl->assign($tpl_data);
            $this->tpl->assign('exist_arr',$result[4]);
            $this->tpl->assign('notexist_arr',$result[5]);
            $this->tpl->display('ExpPrice/index.tpl');//orderlist/chargeslist.tpl
            //$arr_rs = array($arr_deliver 0,$total_money1,$fuman_money2,$chajia_money3,$exist_arr4,$notexist_arr5,$waring_arr6);
        }else{
            echo '请上传需要对帐的帐目文件';
        }
    } 
    
    public function expressCheckHistory(){
        $expresstype=$this->input->get("expresstype");
        $ordertype=$this->input->get("ordertype");
        $deliver_type=array(1=>"顺丰",2=>'UPS',3=>'DHL',4=>'CNE',5=>'UBI',6=>'云途',7=>'燕文',8=>'E邮宝线下上海',9=>"无忧物流",10=>"日本邮政",11=>'CNPOST',12=>'佳成物流',14=>'中通快递','联邦');
        $nowpage = $_REQUEST["pageid"];
        if ($nowpage == "") $nowpage = 1;
        //---处理where查询条件
        //$where = " and express_type>0";// group by express_type,check_month
        $search_data=$this->input->get();
        $starttime_date=date("Y-m-d",strtotime('-1 month'));//默认当月1号开始查询
        $endtime_date=date('Y-m-d');
        $starttime_date=$search_data['starttime']==''?$starttime_date:$search_data['starttime'];
        $endtime_date=$search_data['endtime']==''?$endtime_date:$search_data['endtime'];
        $tpl_data=array('expresstype'=>$expresstype,'ordertype'=>$ordertype,'search'=>$search_data,'deliver_type'=>$deliver_type);
        $orderby=" order by express_type desc,check_month desc";
        if($ordertype!=''){
            $orderby=" order by $ordertype desc";   
        }
        if(!empty($expresstype)){
            $where.=" && express_type=".$expresstype;    
        }
        if(!empty($search_data['program_name'])){
            $where.=" && program_name like '%".$search_data['program_name']."%'";    
        }
		$list = $this->fun->getalllist("db_express_check", $where, $nowpage, $if_csv, $this->pageSize, $orderby,'*');
        
        $total_where=" and express_type>0";// group by express_type,check_month,check_ret
        $total_list=$this->fun->getalllist("db_express_check", $total_where, $nowpage, $if_csv, $this->pageSize, $orderby,'count(id) as datatotal,express_type,check_month,check_ret');
        $new_total_list=array();
        foreach($total_list['list'] as $key=>$val){
            $new_total_list[$val['express_type'].$val['check_month'].$val['check_ret']]=$val;
        }
        $tpl_data['total_list']=$new_total_list;
        $this->tpl->assign($tpl_data);
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        
        $onwers=array(0); //存部门信息
        foreach( $list["list"] as $key=>$program){
            $onwers[]=$program['owner'];
            $list["list"][$key]['create_time']=date("Y-m-d H:i:s",$program['create_time']); 
            $program['ok_data']=$new_total_list[$program['express_type'].$program['check_month']."1"]['datatotal'];
            $program['waring_data']=$new_total_list[$program['express_type'].$program['check_month']."2"]['datatotal']; 
            $program['err_data']=$new_total_list[$program['express_type'].$program['check_month']."3"]['datatotal']; 
            $list["list"][$key]=$program;    
        }
    
         $this->tpl->assign("orderlist", $list["list"]);

        $result_classid = $this->fun->getClassId();//获取部门信息
        $department=array(); //存部门信息
        foreach($result_classid as $key=>$dept){
            $department[$dept['id']]=$dept['name'];        
        }
        
        $this->tpl->display('ExpPrice/expressCheckHistory.tpl');//orderlist/chargeslist.tpl
            
    }  
    
    public function resultCheckdetail(){
         $deliver_type=array(1=>"顺丰",2=>'UPS',3=>'DHL',4=>'CNE',5=>'UBI',6=>'云途',7=>'燕文',8=>'E邮宝线下上海',9=>"无忧物流",10=>"日本邮政",11=>'CNPOST',12=>'佳成物流',14=>'中通快递',15=>'联邦');
         
        $search_data=$this->input->get();
        $where=" and express_type='$search_data[express_type]' and check_month='$search_data[month]' and check_type=1";
        $where=" and id=$search_data[id]";
        $notwhere=" and express_type='$search_data[express_type]' and check_month='$search_data[month]' and check_type=2";
        $total_list=$this->fun->getalllist("db_express_check", $where, 1, $if_csv, 20000, " order by check_ret desc");
        $note_tpl_data=array();
        $note_list=$this->fun->getdatabaseslist("db_express_check", $notwhere);
        foreach($note_list as $key=>$notedata){
            $note_key_val=json_decode($notedata['waring_json'],true);
            $note_tpl_data=array_merge($note_tpl_data,$note_key_val);    
        }
            
        $check_info_list=$waring_arr=$exist_arr=$green_arr=$notexist_arr=array();
        foreach($total_list['list'] as $key=>$checkinfo){
            $exist_infos=json_decode($checkinfo['exist_json'],true);
            $notexist_infos=json_decode($checkinfo['notexist_json'],true);
            foreach($notexist_infos as $notkey=>$ninfo){
                $notexist_infos[$notkey]['weight_waring']=3;
            }
            $exist_infos=$exist_infos==null?array():$exist_infos;
            $check_data=array_merge($notexist_infos,$exist_infos);
            foreach($check_data as $index=>$val){
                $showinfo=array("exl_line"=>$val['id'],"exp_number"=>$val['deliverNumber'],"exp_date"=>$val['deliverDate'],"weight"=>$val['deliverWeight'],
                "fuman_weight"=>$val['weight'],"price"=>$val['deliverFee'],'check_ret'=>$val['weight_waring'],'isform'=>$val['isform'],
                "fuman_price"=>$val['fee'],"order_sn"=>$val['orderId'],'creator'=>$checkinfo['creator'],'createtime'=>$checkinfo['createtime']);
                switch($showinfo['check_ret']){
                    case "1":
                        $waring_arr[]=$showinfo;
                        break;
                    case "2":
                        $green_arr[]=$showinfo;
                        break;
                    case "3":
                        $notexist_arr[]=$showinfo;
                        break;
                    case "":
                        $exist_arr[]=$showinfo;
                        break;
                    break;  
                }  
            
            }
            
        }
        $check_info_list=array_merge($notexist_arr,$waring_arr,$green_arr,$exist_arr);
        $tpl_data=array('list'=>$check_info_list,'note_data'=>$note_tpl_data,
        'deliver_type'=>$deliver_type[$search_data['express_type']],'check_month'=>$search_data['month']);
        $this->tpl->assign($tpl_data);
        $this->tpl->assign("total", count($check_info_list));
        $this->tpl->display('ExpPrice/resultCheckdetail.tpl');
    }
    

    //dhl CNE ubi对帐处理
    public function checkExpPriec($objExcel,$express_type){
        $sheet = $objExcel->getSheet(0);    
        $rows = $sheet->getHighestRow(); //总行数
        $cols = $sheet->getHighestColumn(); //总列数 英文大写字母
        $arrCellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
            'Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU',
            'AV','AW','AX','AY','AZ');
        $cols_length = array_search($cols, $arrCellName); //获取数组下标最大数
        $arr_deliver = array();
        $str_conn = "";
        switch($express_type){
            case "1"://顺丰
            $data_start_row=1;
            $deliverNumber_colnum=2;
            $date_colnum=1;
            $deliverWeight_colnum=5;
            $ddeliverFee_colnum=array(10);
            
            break;
            case "2"://ups
            $data_start_row=1;
            $deliverNumber_colnum=7;
            $date_colnum=6;
            $deliverWeight_colnum=14;
            $ddeliverFee_colnum=array(23);
            break;
            case "3":
            $data_start_row=1;
            $deliverNumber_colnum=1;
            $date_colnum=6;
            $deliverWeight_colnum=8;
            $ddeliverFee_colnum=array(16);
            break;
            case "4"://cne
            $data_start_row=1;
            $deliverNumber_colnum=1;
            $date_colnum=5;
            $deliverWeight_colnum=9;
            $ddeliverFee_colnum=array(10);
            break;
            case "5"://ubi
            $data_start_row=1;
            $deliverNumber_colnum=3;
            $date_colnum=1;
            $deliverWeight_colnum=4;
            $ddeliverFee_colnum=array(15);
            break;
            case "6"://云途交运
            $data_start_row=1;
            $deliverNumber_colnum=0;
            $date_colnum=6;
            $deliverWeight_colnum=10;
            $ddeliverFee_colnum=array(19);
            break;
            case "7"://燕文交运
            $data_start_row=1;
            $deliverNumber_colnum=1;
            $date_colnum=0;
            $deliverWeight_colnum=6;
            $ddeliverFee_colnum=array(13);
            break;
            case "11":
            case "8":// E邮宝线下上海或CNPOST
            $data_start_row=1;
            $deliverNumber_colnum=0;
            $date_colnum=1;
            $deliverWeight_colnum=3;
            $ddeliverFee_colnum=array(7);
            break;
            case "10"://日本邮政
            $data_start_row=1;
            $date_colnum=2;
            $deliverNumber_colnum=1;
            $deliverWeight_colnum=6;
            $ddeliverFee_colnum=array(11);
            break;
            case "12"://佳成物流
            $data_start_row=2;
            $date_colnum=0;
            $deliverNumber_colnum=2;
            $deliverWeight_colnum=5;
            $ddeliverFee_colnum=array(12);
            break;
            case "14":
            $data_start_row=1;
            $date_colnum=1;
            $deliverNumber_colnum=0;
            $deliverWeight_colnum=5;
            $ddeliverFee_colnum=array(6);
            break;
            case "15":
            $data_start_row=1;
            $date_colnum=3;
            $deliverNumber_colnum=0;
            $deliverWeight_colnum=2;
            $ddeliverFee_colnum=array(1);
            break;
        }
        $data_start_row+=1;
        //行
        for($row=$data_start_row;$row<=$rows;$row++){
            $deliverNumber = $sheet->getCell($arrCellName[$deliverNumber_colnum].$row)->getValue();
            if(empty($deliverNumber)){
                continue;
            }
            //列
            for($column=0;$column<= $cols_length;$column++){
                $cellValue = $arrCellName[$column].$row; //A2
                $col_val = $sheet->getCell($cellValue)->getValue();
                $col_val_len = strlen($col_val);
                //运单号
                if($column==$deliverNumber_colnum){
                    $arr_deliver[$row]['deliverNumber'] = trim($col_val);
                    $str_conn.="'".$col_val."'".",";
                }
                //日期
                if($column==$date_colnum){
                    if(is_numeric($col_val)){
                       // $formatcode=$sheet->getCell($cellValue)->getFormatCode();  
                        $col_val=PHPExcel_Style_NumberFormat::toFormattedString($col_val,'Y/m/d');
                    }
                    $arr_deliver[$row]['deliverDate'] = $col_val;
                }
                //称重
                if($column==$deliverWeight_colnum){
                    if(in_array($express_type,array(7,8))){//燕文 e邮宝以克来计算,要换算成千克
                        $col_val=$col_val/1000;  
                    }
                    $arr_deliver[$row]['deliverWeight'] = $col_val;
                }
                //资费
                if(in_array($column,$ddeliverFee_colnum)){
                    if($col_val<0){
                        echo "<script language='javascript'>alert('有为负数的运费信息，请先调整对应的异常信息再上传对帐吧');history.back()</script>";
                        die;
                    }
                    $arr_deliver[$row]['deliverFee'] += $col_val;
                }
            }
        }
        $arr_tmp = array();
        $deliver_sort = array();
        $total_money = 0;
        $fuman_money = 0;
        $chajia_money = 0;
		$straightfee_money=0;
        $str_conn = trim($str_conn,",");
        if(strlen($str_conn)>0){
    		//isform ==1 马帮 isform ==2 新系统 isfrom ==3 海外系统
           $sql = "SELECT batch_shipping_number as shipping_number,batch_orderweight as actionorderweight,freight as shipping_expectfee
           ,batch_order_sn as order_sn,isform from db_mabang_scanorder where batch_shipping_number in ($str_conn) ";
          // echo $sql;
    		//$sql = "SELECT order_id,shipping_number,orderweight,shipping_fee,order_sn, actionorderweight,shipping_expectfee FROM db_order_list WHERE shipping_number in ($str_conn) ";
            $rs  = $this->db->query($sql)->result_array();
            foreach($rs as $key=>$value){
                $arr_tmp[] = $value['shipping_number'];
    			$Newrs[] = $value;
            }
        }
			
          foreach($arr_deliver as $kk=>$vv){
            if(!in_array($vv['deliverNumber'],$arr_tmp)){
					 $newstr_conn.="'".$vv['deliverNumber']."'".",";
			}
		  }
		$newstr_conn = trim($newstr_conn,",");
        //echo $newstr_conn;
        if(strlen($newstr_conn)>0){
    		$sql = "SELECT ck as shipping_number,weight as actionorderweight,A.freight as shipping_expectfee,
            tasknumber as order_sn,task_id from t_transport_status A left join t_transportationtask B on A.task_id = B.id where ck in ($newstr_conn) ";
            $rsdb  = $this->db->query($sql)->result_array();
            foreach($rsdb as $key=>$value){
    			$value['isform'] = 3;
    			$value['order_snid'] = $value['task_id'];
                $arr_tmp[] = $value['shipping_number'];
    			$Newrs[] = $value;
            }
            
            $sql = "SELECT order_id,shipping_number,orderweight,shipping_fee,order_sn,
             actionorderweight,shipping_expectfee FROM db_order_list WHERE shipping_number in ($newstr_conn)";
            $rsdb  = $this->db->query($sql)->result_array();
            foreach($rsdb as $key=>$value){
    			$value['isform'] = 2;
                $arr_tmp[] = $value['shipping_number'];
    			$Newrs[] = $value;
            }
        }
        $real_straightfee=0;$green_ships=array();
        $notexist_money=0;
        foreach($arr_deliver as $kk=>$vv){
            if(in_array($vv['deliverNumber'],$arr_tmp)){
                //获取键值
                $key = array_search($vv['deliverNumber'],$arr_tmp);
				if($Newrs[$key]['isform']==3)
				{
					$weight = $Newrs[$key]['actionorderweight'];
                    $change_weight=$weight;
					if($Newrs[$key]['shipping_expectfee'])
					{
						$fee = $Newrs[$key]['shipping_expectfee'];
					}else{
						$fee =0;
					}
					$arr_deliver[$kk]['oId']= $Newrs[$key]['order_snid'];
                    $straightfee = $Newrs[$key]['shipping_expectfee'];	//直发费用
                    $real_straightfee+=$vv['deliverFee'];
				}else{
					$weight = $Newrs[$key]['actionorderweight']/1000;
                    if(in_array($express_type,array(1,2,3))){
                        $change_weight=ceil($weight/0.5)*0.5;
                    }else{
                        $change_weight=$weight;   
                    }
					$fee = $Newrs[$key]['shipping_expectfee'];
				}
                
                $order_sn = $Newrs[$key]['order_sn'];
                $arr_deliver[$kk]['dataid']=$vv['order_id'];
                $arr_deliver[$kk]['id']=$kk;
                $arr_deliver[$kk]['deliverNumber']=$vv['deliverNumber'];
                $arr_deliver[$kk]['deliverFee']=$vv['deliverFee'];
                $arr_deliver[$kk]['deliverWeight']=$vv['deliverWeight'];
                //复漫
                $arr_deliver[$kk]['orderId']= $order_sn;
                $arr_deliver[$kk]['fee']= $fee;
                $arr_deliver[$kk]['weight']= $weight;
				$arr_deliver[$kk]['isform']= $Newrs[$key]['isform'];
                $total_money = $total_money+$vv['deliverFee'];
                $fuman_money = $fuman_money+$fee;
				 $straightfee_money = $straightfee_money+$straightfee;//直发费用
                $chajia_money= $chajia_money+$vv['deliverFee'];
                //sort
                $deliver_sort[$kk] = $order_sn;
                $deliverWeight=$vv['deliverWeight']*1000;
                $arr_plat['shipping_realfee']=$vv['deliverFee'];
                $arr_plat['orderweight']=$deliverWeight;
                $checktype=$this->input->post('checktype');
                if($vv['deliverWeight']){
                    $info_weight=($vv['deliverWeight']-$change_weight)/$vv['deliverWeight'];
                      
                }
                if($info_weight>0.10)$arr_deliver[$kk]['weight_waring']=1;
                if($info_weight<-0.10)$arr_deliver[$kk]['weight_waring']=2;
                $exist_arr[]=$arr_deliver[$kk]; 
                if($info_weight>0.10 || $info_weight<-0.10){//|| $info_fre>0.10
                    //if($info_fre>0.10)$arr_deliver[$kk]['fre_waring']=1;
                    if($info_weight<-0.10){
                        $green_ships[]=$arr_deliver[$kk];
                        unset($arr_deliver[$kk]);    
                    }else{
                        $waring_arr[]=$arr_deliver[$kk];
                        unset($arr_deliver[$kk]);     
                    }  
                }             
            }else{
				//获得海外运单
                $arr_deliver[$kk]['id']=$kk;
                $arr_deliver[$kk]['deliverNumber']=$vv['deliverNumber'];
                $arr_deliver[$kk]['deliverFee']=$vv['deliverFee'];
                $arr_deliver[$kk]['deliverWeight']=$vv['deliverWeight'];
                $arr_deliver[$kk]['orderId']= "";
                $arr_deliver[$kk]['fee']= 0;
                $arr_deliver[$kk]['weight']= 0;
                $total_money = $total_money+$vv['deliverFee'];
                $fuman_money = $fuman_money+0;
                $chajia_money= $chajia_money+0;
                $notexist_money+=$vv['deliverFee'];
                $deliver_sort[$kk] = "";
                $notexist_arr[]=$arr_deliver[$kk];
                unset($arr_deliver[$kk]);
            }
        }
        $only_send_fre=$total_money-$real_straightfee-$notexist_money;
        $totalinfo=array("id"=>'合计',"deliverFee"=>$total_money,'fee'=>"海外费用:{$real_straightfee}"."，直发费用{$only_send_fre}");//'deliverWeight'=>"直发费用{$only_send_fre}"
        $arr_deliver[]=$totalinfo;
        //@array_multisort($deliver_sort,SORT_ASC,$arr_deliver); //排序
        //print_r($sql);//exit;
        if(!is_array($green_ships)){$green_ships=array();}
        if(!is_array($waring_arr)){$waring_arr=array();}
        $check_datas=array('waring_total'=>count($waring_arr),'zhifa_money'=>$only_send_fre,'haiwai_money'=>$real_straightfee,"waring_arr"=>$waring_arr,"green_arr"=>$green_ships);
        $waring_arr=array_merge($waring_arr,$green_ships);
        $arr_rs = array($arr_deliver,$total_money,$fuman_money,$chajia_money,$exist_arr,$notexist_arr,$waring_arr,$check_datas);
        return $arr_rs;  
    }
    
    public function updateCheckResult(){
        $deliverType=$_POST['deliverType'];
        $selectMonth=$_POST['selectMonth'];
        set_time_limit(0);
        $deliver_type=array(1=>"顺丰",2=>'UPS',3=>'DHL',4=>'CNE',5=>'UBI',6=>'云途',7=>'燕文',8=>'E邮宝线下上海或CNPOST',9=>"无忧物流",10=>"日本邮政",11=>'CNPOST',12=>'佳成物流',14=>'中通快递');
        $arr_excel_file = $_FILES['file_excel'];
        if(!empty($arr_excel_file) && $arr_excel_file['error']==0) {
            require dirname(__FILE__)."/../../fuman/ClassesExcel/PHPExcel.php";
            $fileName = $arr_excel_file["name"];
            $tmpFileName = $arr_excel_file["tmp_name"];
            $fileExtName = explode(".", $fileName);
            if (!($fileExtName[1] == "xls" || $fileExtName[1] == "xlsx")) {//扩展名判断
                echo "上传的文件扩展名应该为.xls或.xlsx";
                exit;
            }
            if ($fileExtName[1] == 'xlsx') {
                $objReader = new PHPExcel_Reader_Excel2007();
                $objExcel = $objReader->load($tmpFileName);
            } else if ($fileExtName[1] == 'xls') {
                $objReader = new PHPExcel_Reader_Excel5();
                $objExcel = $objReader->load($tmpFileName);
            }

            $sheet = $objExcel->getSheet(0);    
            $rows = $sheet->getHighestRow(); //总行数
            $cols = $sheet->getHighestColumn(); //总列数 英文大写字母
            $arrCellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
                'Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU',
                'AV','AW','AX','AY','AZ');
            $cols_length = array_search($cols, $arrCellName); //获取数组下标最大数
            $check_data = array();
            $str_conn = "";
            $data_start_row=2;
            //行
            for($row=$data_start_row;$row<=$rows;$row++){
                $deliverNumber = $sheet->getCell($arrCellName[1].$row)->getValue();//运单号为空则退出
                if(empty($deliverNumber)){
                    continue;
                }
                $rowval=array();
                //列
                for($column=0;$column<= 8;$column++){
                    $cellValue = $arrCellName[$column].$row; //A2
                    $col_val = $sheet->getCell($cellValue)->getValue();
                    if($col_val instanceof PHPExcel_RichText){   
                        $col_val = $col_val->__toString();  
                    }
                    $colnum_name=array("exl_line","exp_number","exp_date","weight","fuman_weight","price","fuman_price","order_sn","note");
                    $col_val=$col_val==null?'':$col_val;
                    $rowval[$colnum_name[$column]]=$col_val;
                    $rowval['creator']=$_COOKIE['username'];
                    $rowval['createtime']=date("Y-m-d H:i:s");
                }
                $check_data[]=$rowval;
            }
        
            $web_title=$deliver_type[$deliver_type_val]."对帐结果";
            $this->tpl->assign('web_title',$web_title);
            $alldata_json=json_encode($check_data);
       
            $tpl_data=array("alldata_json"=>$alldata_json,'notexistdata'=>$check_data);
            
            $this->tpl->assign($tpl_data);
            $this->tpl->assign('express_type',$deliverType);
            $this->tpl->assign('month',$selectMonth);
            $this->tpl->assign('exist_arr',$result[4]);
            $this->tpl->assign('notexist_arr',$result[5]);
            $this->tpl->display('ExpPrice/resultCheckList.tpl');//orderlist/chargeslist.tpl
        }else{
            //selectExpressCheckInfo
            $check_month=$_GET['month'];
            $exptype=$_GET['express_type'];
            $selectExpressCheckInfo=$deliver_type[$exptype]." ".$check_month."对帐信息";
            $this->tpl->assign('express_type',$exptype);
            $this->tpl->assign('month',$check_month);
            $this->tpl->assign('selectExpressCheckInfo',$selectExpressCheckInfo);
            $this->tpl->display('ExpPrice/uploadCheckResult.tpl');
        }
    }
    
    
    
    public function doUpdateCheckResult(){
        set_time_limit(0);
        $deliverType=$_POST['deliverType'];
        $selectMonth=$_POST['selectMonth'];
        $expo_shipment_json=$_POST["up_expdata"];
        $exporderlist=json_decode($expo_shipment_json,true);
        $check_express_list=$note_arr=array();
        foreach($exporderlist as $key=>$val){
            if(!empty($val['note'])){
                $check_express_list[]=$val;
                $note_arr[$val['exp_number']]=$val['note'];
            }
        }
        
        //dump($_POST);
        $shipment_list=json_encode($check_express_list);
        $waring_json=json_encode($note_arr);
        $check_data=array('exl_line'=>0,'exist_json'=>$shipment_list,'waring_json'=>$waring_json,'check_type'=>2,
        'check_month'=>$selectMonth,'express_type'=>$deliverType,'creator'=>$_COOKIE['username'],'createtime'=>date("Y-m-d H:i:s"));
       // dump($check_data);
        $this->db->insert('db_express_check', $check_data);
        
        /*
        $adddata=array('needstore_json'=>$exporderlist,'creator'=>$_COOKIE['username'],'createtime'=>date("Y-m-d H:i:s"));
        foreach($exporderlist as $key=>$val){
            if(!empty($val['note'])){
                $have_shipinfo=$this->fun->getdatabasesdetail('db_express_check',
                " AND exp_number='".$val['exp_number']."' and exl_line=$val[exl_line]");
                if($have_shipinfo['id']){
                    //unset($val['creator']);
                    $this->db->update('db_express_check', $val,' id='.$have_shipinfo['id']);  
                    //echo $this->db->last_query();   
                }else{
                    $this->db->insert('db_express_check', $val);     
                }  
            }
        }
        //$have_shipinfo=;
        echo $this->db->last_query();*/
        echo "<script language='javascript'>alert('异常运单备注成功');</script>";//location.href='/sales/storeNeedList';
    }
    
    public function updateRealExpPrice(){
        set_time_limit(0);
        $exporder=$this->input->post("up_expdata");
        $diff_data=$this->input->post("diff_data");//
        $selectMonth=$this->input->post("selectMonth");
        $deliverType=$this->input->post("deliverType");
        $point_val=$this->input->post('point');
        if($point_val>=2 || $point_val<=0.4){
            die("折扣数据异常，大于等于2倍或小于0.4了");    
        }
        $exporderlist=json_decode($exporder,true);
        $diff_data_list=json_decode($diff_data,true);
        //isform ==1 马帮 isform ==2 新系统 isfrom ==3 海外系统
        $express_check_arr=array();
        //$sqlCount ="delete from db_express_check where check_month='$selectMonth' and express_type=$deliverType";
        //$allCount = $this->db->query($sqlCount);
        
            
        $check_data=array('exl_line'=>0,'exist_json'=>$exporder,'notexist_json'=>$diff_data,'zhifa_money'=>$_POST['zhifa_money'],
        'haiwai_money'=>$_POST['haiwai_money'],'exist_total'=>count($exporderlist),'total_money'=>$_POST['total_money'],
        'weightwaring_total'=>$_POST['waring_total'],'notexist_total'=>$_POST['notexist_total'],'point'=>$point_val,
        'check_month'=>$selectMonth,'express_type'=>$deliverType,'creator'=>$_COOKIE['username'],'createtime'=>date("Y-m-d H:i:s"));
        $this->db->insert('db_express_check', $check_data);
         //'point'=>$point_val,
        /*                
        foreach($diff_data_list as $key=>$val){
            $check_ret=$val['weight_waring']==1?2:3;//
            if($check_ret==2){
                continue;
            }
            $diffinfo=array("exl_line"=>$val['id'],"exp_number"=>$val['deliverNumber'],"exp_date"=>$val['deliverDate'],"weight"=>$val['deliverWeight'],
            "fuman_weight"=>$val['weight'],"price"=>$val['deliverFee'],'check_ret'=>$check_ret,'check_month'=>$selectMonth,
            "fuman_price"=>$val['fee'],"order_sn"=>$val['orderId'],'express_type'=>$deliverType,
            'creator'=>$_COOKIE['username'],'createtime'=>date("Y-m-d H:i:s")
            );
            $express_check_arr[]=$diffinfo;
        }
        foreach($express_check_arr as $key=>$val){
            $this->db->insert('db_express_check', $val);      
        }
        if(!is_array($exporderlist)){
            $exporderlist=array();
        }
        foreach($exporderlist as $key=>$expinfo){
            $val=$expinfo;
            echo $key."正在更新运单号：".$expinfo['deliverNumber']."运费信息<br />";
            switch($expinfo['isform']){
                case "1":
                case "2":
                    $deliverWeight=$expinfo['deliverWeight']*1000;
                    $scanorder_updata=array("real_freight"=>$expinfo['deliverFee']);
                    $this->db->update('db_mabang_scanorder',$scanorder_updata,"batch_shipping_number='".$expinfo['deliverNumber']."'");
                    //dump($this->db->last_query()); 
                    $rsOrder = $this->fun->getdatabasesdetail('db_order_list'," AND shipping_number='".$expinfo['deliverNumber']."'");
                    //dump($this->db->last_query());
                    if($rsOrder){
                        $arr_plat['shipping_realfee']=$expinfo['deliverFee']*$point_val;
                        $arr_plat['orderweight']=$deliverWeight;
                        $this->db->update('db_order_list',$arr_plat,"shipping_number='".$expinfo['deliverNumber']."'"); //更新物流费用
                        //dump($this->db->last_query());
                        $logdata["goods_id"] = $rsOrder['order_id'];	//订单ID db_order_list
                        $logdata["updatetime"] = date("Y-m-d H:i:s");
                        $logdata["createUid"] = $_COOKIE['userid'];
                        $logdata["types"] = 3;
                        $logdata["content"] = '交运对帐，更新真实物流费为：'.$arr_plat['shipping_realfee'].',预估重量更新为对方称重：'.$deliverWeight;
                        $logdata["createUser"] =$_COOKIE['username'];
                        $this->db->insert('db_goods_log', $logdata); 
                        //dump($this->db->last_query());
                    }
                break;
                case "3":
                    $box_expinfo= $this->fun->getdatabasesdetail('t_transport_status'," AND ck='".$expinfo['deliverNumber']."'");
                    //dump($this->db->last_query());
                    if($box_expinfo['task_id']){
                        $transport_status_updata=array('freight'=>$expinfo['deliverFee']);
                        $this->db->update('t_transport_status',$transport_status_updata,"ck='".$expinfo['deliverNumber']."'");
                        //dump($this->db->last_query());
                        $sql = "SELECT sum(A.freight) as real_free,ck,task_id from t_transport_status A
                        left join t_transportationtask B on A.task_id = B.id where A.task_id=".$box_expinfo['task_id'];
                        $rsdb = $this->db->query($sql)->result_array();
                       // dump($this->db->last_query());
                        //dump($rsdb);
                        if($rsdb[0]['task_id']){
                            $task_updata=array('actual_freight'=>$rsdb[0]['real_free']);
                            $this->db->update('t_transportationtask',$task_updata,"id=".$rsdb[0]['task_id']);    
                        }
                       // dump($this->db->last_query());
                    }
                break;              
            }
            //做备忘数据
            $check_ret=$val['weight_waring']==1?2:1;//
            $diffinfo=array("exl_line"=>$val['id'],"exp_number"=>$val['deliverNumber'],"exp_date"=>$val['deliverDate'],"weight"=>$val['deliverWeight'],
            "fuman_weight"=>$val['weight'],"price"=>$val['deliverFee'],'check_ret'=>$check_ret,'check_month'=>$selectMonth,
            "fuman_price"=>$val['fee'],"order_sn"=>$val['orderId'],'express_type'=>$deliverType,
            'creator'=>$_COOKIE['username'],'createtime'=>date("Y-m-d H:i:s"));
             $this->db->insert('db_express_check', $diffinfo);     
        }*/
        echo "<strong><br />对帐数据存储成功，稍后我们将开始更新真实物流费用，您可以到交运对帐记录里查看更新结果</strong><br />
            <a href='/CheckExpressPrice/expressCheckHistory'>前往查看交运对帐记录</a>";
    }
    
    public function outputExl2(){
        require dirname(__FILE__)."/../../fuman/ClassesExcel/PHPExcel.php";
        //.....此处略去从数据库获取数据的过程，$a为需要导出的数组......
        $filename=$this->input->post("filename");
        $outputinfo=$this->input->post("htmldata");
       
        $outputinfo_data=json_decode($outputinfo,true);
        //dump($outputinfo_data);die;
        $a=array();
        foreach($outputinfo_data as $akey=>$aval){
            $a[]=$aval;    
        }
        $numArr = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');
        // Create new PHPExcel object
        $objPHPExcel = new PHPExcel();

        $arr = array('EXCEL行号','运单号','发件日期','重量', '复漫称重', '资费', '复漫预估运费', '复漫订单号','备注（填写项）');
        // 输出标题
        //echo date('H:i:s') , " Add some data" , EOL;
        //设置换行
        //$objPHPExcel->getActiveSheet()->getStyle('H')->getAlignment()->setWrapText(true);
        $objPHPExcel->getActiveSheet()->getStyle('Y')->getAlignment()->setWrapText(true);
        //设置相应列的宽度
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('A')->setWidth(10);
        //weight_waring
        
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('C')->setWidth(15);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('G')->setWidth(15);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('H')->setWidth(25);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('I')->setWidth(15);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('J')->setWidth(15);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('K')->setWidth(25);
        //输出第一行
        $objPHPExcel->setActiveSheetIndex(0)
           ->setCellValue('A1', $arr[0])
         ->setCellValue('B1', $arr[1])
         ->setCellValue('C1', $arr[2])
         ->setCellValue('D1', $arr[3])
         ->setCellValue('E1', $arr[4])
         ->setCellValue('F1', $arr[5])
         ->setCellValue('G1', $arr[6])
         ->setCellValue('H1', $arr[7])
         ->setCellValue('I1', $arr[8])
         ->setCellValue('J1', $arr[9])
           ->setCellValue('K1', $arr[10])
           ->setCellValue('L1', $arr[11]);
         
         
        //输出内容
        for($i=0;$i<count($a);$i++){
         
          $td_color=$a[$i]['orderId']==''?"FF0000":$a[$i]['weight_waring']==1?"FF9900":'33CC00';
          if($a[$i]['orderId']==''){
            $td_color='FF0000';  
          }
          if($a[$i]['orderId']!='' and $a[$i]['weight_waring']=='' ){
            $td_color='000000';  
          }

          $objPHPExcel->getActiveSheet()->getStyle($numArr[0].($i+2))->getFont()->getColor()->setARGB("00".$td_color);
         $objPHPExcel->setActiveSheetIndex(0)
          ->setCellValue($numArr[0].($i+2), $a[$i]['id'])
          ->setCellValueExplicit($numArr[1].($i+2), $a[$i]['deliverNumber'])
          ->setCellValue($numArr[2].($i+2), $a[$i]['deliverDate'])
          ->setCellValue($numArr[3].($i+2), $a[$i]['deliverWeight'])
          ->setCellValue($numArr[4].($i+2), $a[$i]['weight'])
          ->setCellValue($numArr[5].($i+2), $a[$i]['deliverFee'])
          ->setCellValue($numArr[6].($i+2), $a[$i]['fee'])
          ->setCellValueExplicit($numArr[7].($i+2), $a[$i]['orderId'])
          ->setCellValue($numArr[8].($i+2), '')
          //->setCellValue($numArr[9].($i+2), $td_color)
          ->setCellValue($numArr[10].($i+2), '');
          
        }
         
        // Rename worksheet
        //echo date('H:i:s') , " Rename worksheet" , EOL;
        $dirName ="dhlexpress";//目录名
        $old_filename=$filename;
        //$filename = iconv("utf-8","gb2312//IGNORE",$filename);
        $fileName = "checkresult";//文件名\uploads\DHL
        $objPHPExcel->getActiveSheet()->setTitle('Sheet1');
         
         
        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $objPHPExcel->setActiveSheetIndex(0);
         
        // Save Excel 2007 file
        //echo date('H:i:s') , " Write to Excel2007 format" , EOL;
        $callStartTime = microtime(true);
        if(!opendir(dirname(__FILE__).'/../../uploads/'.$dirName)){
            mkdir(dirname(__FILE__).'/../../uploads/'.$dirName);
        }
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save(dirname(__FILE__).'/../../uploads/'.$dirName.'/'.$fileName.'.xlsx');
         
        header('Location:http://'.$_SERVER['HTTP_HOST'].'/uploads/'.$dirName.'/'.$fileName.'.xlsx');
    }
    
    public function autoUpdateRealShipFre(){ 
        set_time_limit(0);
        $site_root=$_SERVER['DOCUMENT_ROOT']; 
        $point_val=1;
        //isform ==1 马帮 isform ==2 新系统 isfrom ==3 海外系统       
        if(!is_array($exporderlist)){
            $exporderlist=array();
        }
        
        $needUpdateOrders= $this->fun->getdatabaseslist("db_express_check"," and check_type=1 && update_type<1","*","order by id asc");
        //getdatabasesdetail('db_express_check'," and check_type=1 && id>'$dataid'","*","order by id asc"); 
        foreach($needUpdateOrders as $key=>$checkdata){
            $exporderlist=json_decode($checkdata['exist_json'],true);
            $exporderlist=$this->arraySort($exporderlist,'id');
            
            if(!is_array($exporderlist)){
                $exporderlist=array();
            }

            foreach($exporderlist as $key=>$expinfo){
                $val=$expinfo;
                //echo $key."正在更新运单号：".$expinfo['deliverNumber']."运费信息<br />";
                if($expinfo['id']<$uporderid){//已经更新过的跳过处理
                    //echo "continue<br />";
                    continue;
                }
                switch($expinfo['isform']){
                    case "1":
                    case "2":
                        $deliverWeight=$expinfo['deliverWeight']*1000;
                        $scanorder_updata=array("real_freight"=>$expinfo['deliverFee']);
                        $scanorder_updatas[$expinfo['deliverNumber']]=array("real_freight"=>$expinfo['deliverFee'],
                        'batch_shipping_number'=>$expinfo['deliverNumber']);
                        //$this->db->update('db_mabang_scanorder',$scanorder_updata,"batch_shipping_number='".$expinfo['deliverNumber']."'");
                        //dump($this->db->last_query());
                        $arr_plat['shipping_realfee']=$expinfo['deliverFee']*$point_val;
                        $arr_plat['orderweight']=$deliverWeight;$arr_plat['shipping_number']=$expinfo['deliverNumber'];
                        $arr_plats[]=$arr_plat;
                        //$this->db->update('db_order_list',$arr_plat,"shipping_number='".$expinfo['deliverNumber']."'"); //更新物流费用
                       // dump($this->db->last_query());
                    break;
                    case "3":
                        $box_expinfo= $this->fun->getdatabasesdetail('t_transport_status'," AND ck='".$expinfo['deliverNumber']."'");
                        //dump($this->db->last_query());
                        if($box_expinfo['task_id']){
                            $transport_status_updata=array('freight'=>$expinfo['deliverFee'],'ck'=>$expinfo['deliverNumber']);
                            $transport_status_updatas[]=$transport_status_updata;
                            
                            $sql = "SELECT sum(A.freight) as real_free,ck,task_id from t_transport_status A
                            left join t_transportationtask B on A.task_id = B.id where A.task_id=".$box_expinfo['task_id'];
                            $rsdb = $this->db->query($sql)->result_array();
                           // dump($this->db->last_query());
                            //dump($rsdb);
                            if($rsdb[0]['task_id']){
                                $task_updata=array('actual_freight'=>$rsdb[0]['real_free'],'id'=>$rsdb[0]['task_id']);
                                $task_updatas[]=$task_updata;
                                //$this->db->update('t_transportationtask',$task_updata,"id=".$rsdb[0]['task_id']);    
                            }
                           // dump($this->db->last_query());
                        }
                    break;              
                }

            }
            if(count($arr_plats)>0){
                $scanorder_shipmembers=iarray_column($scanorder_updatas,'batch_shipping_number');
                $shipmember_str=implode("','",$scanorder_shipmembers);
                $scanorders=$this->fun->getdatabaseslist("db_mabang_scanorder"," and batch_shipping_number in ('".$shipmember_str."')","*");
                foreach($scanorders as $index=>$rs){
                    $freight=$rs['freight']=='没有填写运费计算公式'?"0":$rs['freight'];
                    $lastprice = $rs["MONEYASK"]+$rs["MONEYEXPRESSASK"]-$rs["MONEYACTION"]-$rs['FINALVALUEFEE'] - 
                    $rs['PAYPALFEEAMOUNT']-$scanorder_updatas[$rs['batch_shipping_number']]['real_freight'];
                    if($rs["MONEYASK"]+$rs["MONEYEXPRESSASK"]>0){
                        $maolilv=round($lastprice/($rs["MONEYASK"]+$rs["MONEYEXPRESSASK"]),4)*100; 
                        $scanorder_updatas[$rs['batch_shipping_number']]['maolilv']=$maolilv; 
                    }
                    $scanorder_updatas[$rs['batch_shipping_number']]['freight']=$freight;
                    $scanorder_updatas[$rs['batch_shipping_number']]['maoli']=$lastprice;
                }
                
                $this->db->update_batch('db_mabang_scanorder', $scanorder_updatas, 'batch_shipping_number');//批量更新
                $this->db->update_batch('db_order_list', $arr_plats, 'shipping_number');//批量更新    
            }
            if(count($transport_status_updatas)>1){
                $this->db->update_batch('t_transport_status', $transport_status_updatas, 'ck');//批量更新    
            }
            if(count($task_updatas)>1){
                $this->db->update_batch('t_transportationtask', $task_updatas, 'id');//批量更新
            }

            $this->db->update('db_express_check',array('update_type'=>1),"id=".$checkdata['id']); 
         
            
        }
        echo "<strong><br />所有真实物流费用更新成功</strong>";
    }
    
    /**
     * @desc arraySort php二维数组排序 按照指定的key 对数组进行排序
     * @param array $arr 将要排序的数组
     * @param string $keys 指定排序的key
     * @param string $type 排序类型 asc | desc
     * @return array
     */
    function arraySort($arr, $keys, $type = 'asc') {
        $keysvalue = $new_array = array();
        foreach ($arr as $k => $v){
            $keysvalue[$k] = $v[$keys];
        }
        $type == 'asc' ? asort($keysvalue) : arsort($keysvalue);
        reset($keysvalue);
        foreach ($keysvalue as $k => $v) {
           $new_array[$k] = $arr[$k];
        }
        return $new_array;
    }
}
